<template>
<view class="container" :style="'background:' +setting.platformSetting.defaultColor">
  <view class="coupon_content">
    <view class="coupon_top">
      <view class="coupon_shop_logo">
        <image v-if="couponDetail.shopLogo" :src="couponDetail.shopLogo"></image>
        <image v-else :src="setting.platformSetting.logo"></image>
      </view>
      <view class="coupon_shop_name">
        <text v-if="couponDetail.belongShopName">{{couponDetail.belongShopName}}</text>
        <text v-else>{{setting.platformSetting.platformName}}</text>
      </view>
      <view class="coupon_detail">
        <view class="coupon_detail_name">{{couponDetail.name}}</view>
        <view class="coupon_detail_count">
          <view class="coupon_detail_condition">
            <text v-if="couponDetail.orderAmount==0">无最低消费</text>
            <text v-else>满{{couponDetail.orderAmount}}可使用</text>
          </view>
          <text class="coupon_detail_count_num" v-if="couponDetail.count!=0">剩余{{couponDetail.count-couponDetail.gotCount}}张</text>
          <text class="coupon_detail_count_num" v-else>无限量</text>
        </view>
        <view class="coupon_detail_botton" v-if="showBtn">
        <!--   -->
          <view class="coupon_detail_botton_now" @tap="selectFun" :style="'background:' + color + ';border:2rpx solid ' + color">
            <text v-if="!couponState&&couponEnableState">立即领取</text>
            <text v-if="couponState&&couponEnableState&&couponUserState">立即使用</text>
            <text v-if="!couponEnableState&&!couponCountState">已领完</text>
            <text v-if="!couponEnableState&&!couponTimetState">已过期</text>
            <text v-if="!couponUserState&&couponEnableState">已使用过</text>
          </view>
          <view class="coupon_detail_botton_free" @tap="gotoGetCoupon"><text>免费领券</text></view>
        </view>
      </view>
    </view>
    <view class="coupon_bottom">
      <view class="line_round">
        <view class="round" :style="'background:' +setting.platformSetting.defaultColor+';left: -18rpx;'"></view>
        <view class="line"></view>
        <view class="round" :style="'background:' +setting.platformSetting.defaultColor"></view>
      </view>
      <view class="coupon_detail_limit">
        <view class="dot"></view>
        <text style="margin-left:20rpx;" v-if="couponDetail.endDateType==1">领取后{{couponDetail.endDateCount}}天内有效</text>
        <text style="margin-left:20rpx;" v-else>领取后，有效期为{{couponDetail.endDate}}为止</text>
      </view>
      <view class="coupon_detail_Welcome" @tap="gotoGetCoupon"><text>欢迎光临本店，浏览更多优惠</text><view class="more">></view></view>
      <view class="coupon_detail_describe">
        <view class="coupon_detail_describe_title"><text>使用须知</text></view>
        <view class="coupon_detail_describe_content">
          <view class="dot"></view>
          <text style="margin-left:20rpx;">{{couponDetail.remark}}</text>
        </view>
      </view>
    </view>
  </view>
  <view class="more_coupons" @tap="gotoGetCoupon">
    <text>更多优惠券</text>
  </view>
</view>
</template>

<script>

export default {
  data() {
    return {
      couponDetail: null,
      color: '#e2534d',
      couponUserState: true,
      couponEnableState: true,
      couponState: true,
      couponCountState: true,
      couponTimetState: true,
      clickStyle: 'receive',
      showBtn: false,
      optParam: {},
      setting: "",
      loginUser: "",
      sysWidth: "",
      sysHeight: ""
    };
  },

  components: {},
  props: {},
  // option数据 用来转发和刷新
  onLoad: function (options) {
    console.log("===options===", options);
    this.optParam = options;
    let showBtn = false;

    if (options.type == 'jifen') {
      showBtn = false;
    } else {
      showBtn = true;
    }

    this.setData({
      showBtn: showBtn
    });
    this.getData(options);
  },
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      loginUser: getApp().globalData.loginUser,
      sysWidth: getApp().globalData.sysWidth,
      sysHeight: getApp().globalData.sysHeight
    });
    console.log('setting', this.setting);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData(this.optParam);
    wx.stopPullDownRefresh();
  },
  methods: {
    getData: function () {
      let that = this;
      let customIndex = getApp().globalData.AddClientUrl("/get_coupon_detail.html", that.optParam, 'get');
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          that.setData({
            couponDetail: res.data.relateObj
          });

          if (that.couponDetail.isusing == 1) {
            console.log('可用');
            that.setData({
              couponEnableState: true
            }); //1可用

            that.setData({
              color: '#e2534d'
            });

            if (that.couponDetail.userGotCoupon.length != 0) {
              that.setData({
                clickStyle: 'used'
              }); //点击类型

              that.setData({
                couponState: true
              }); //已领取

              wx.showToast({
                title: '你已经领过了',
                icon: 'success',
                duration: 2000
              });

              if (that.couponDetail.userGotCoupon[0].isUsed == 0) {
                that.setData({
                  couponUserState: true
                }); //0未使用

                that.setData({
                  color: '#e2534d'
                });
              } else {
                that.setData({
                  couponUserState: false
                }); //已使用

                that.setData({
                  color: '#E7E7E7'
                });
                that.setData({
                  clickStyle: 'noClick'
                }); //点击类型
              }
            } else {
              that.setData({
                couponState: false
              }); //未领取

              that.setData({
                clickStyle: 'receive'
              });
            }
          } else {
            console.log('不可用');
            that.setData({
              couponEnableState: false
            }); //不可用

            that.setData({
              color: '#E7E7E7'
            });
            that.setData({
              clickStyle: 'noClick'
            }); //点击类型

            if (that.couponDetail.count != 0 && that.couponDetail.count <= that.couponDetail.gotCount) {
              that.setData({
                couponCountState: false
              }); //已领完
            } else {
              that.setData({
                couponCountState: true
              }); //已领完
            }

            let nowData = new Date();
            let couponData = that.couponDetail.endDate;
            couponData = couponData.replace(/-/g, "/");
            couponData = new Date(couponData);
            console.log('===couponData===', couponData);
            console.log('===nowData===', nowData);
            let days1 = parseInt(couponData.getTime() / (1000 * 60 * 60 * 24));
            let days2 = parseInt(nowData.getTime() / (1000 * 60 * 60 * 24));
            console.log('===days1===', days1, days2);

            if (days1 > days2) {
              that.setData({
                couponTimetState: true
              }); //未到期
            } else {
              that.setData({
                couponTimetState: false
              }); //已到期
            }
          }

          console.log(that.couponDetail);
          wx.hideLoading();
        },
        fail: function (res) {
          console.log('fail');
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    selectFun: function () {
      let that = this;

      if (that.clickStyle == 'receive') {
        that.gainCoupon();
      } else if (that.clickStyle == 'used') {
        getApp().globalData.toIndex();
      } else {
        console.log('不可点击');
        return;
      }
    },
    gainCoupon: function () {
      let that = this;
      let customIndex = getApp().globalData.AddClientUrl("/gain_coupon.html", that.optParam, 'post');
      console.log("customIndex", customIndex);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        method: 'POST',
        header: getApp().globalData.headerPost,
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode && res.data.errcode == -1) {
            console.log('===1====');
            wx.showToast({
              title: res.data.relateObj,
              icon: 'success',
              duration: 1000
            });
          } else if (!res.data.errcode) {
            console.log('===2====');

            if (res.data.newGot == 0 && res.data.otherGot == 0) {
              wx.showToast({
                title: '你已经领过了',
                icon: 'success',
                duration: 1000
              });
            } else if (res.data.otherGot == 1) {
              wx.showToast({
                title: '已被别人领取',
                icon: 'success',
                duration: 1000
              });
            } else if (res.data.newGot == 1) {
              wx.showToast({
                title: '领取成功',
                icon: 'success',
                duration: 1000
              });
              that.setData({
                couponState: true
              }); //已领取

              that.setData({
                clickStyle: 'used'
              }); //点击类型
            }
          }
        },
        fail: function (res) {
          console.log('fail');
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 组件事件集合 */
    tolinkUrl: function (e) {
      let linkUrl = e.currentTarget?e.currentTarget.dataset.link:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    toCouponList: function (event) {
      console.log("--------toCouponList------");
      let that=this;
      that.tolinkUrl("my_coupons.html")
    },
    gotoGetCoupon: function () {
      let that=this;
      that.tolinkUrl("available_coupons.html")
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>